const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class GradeService extends Service {
  /**
   * * 课程成绩查询
   * @param {String} term 学期
   * @return {Array} *
   */
  async table(term = 'all') {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kscj/cjcx_list`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        kksj: '',
        kcxz: '',
        kcmc: '',
        xsfs: term,
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        const columnNeed = [3, 13, 7, 5, 8, 11, 14, 9, 4, 15] // 需要提取的列序号
        const header = ['课程名称', '类型', '学分', '成绩', '总学时', '考核方式', '课程性质', '绩点', '分组名', '通选课类型'] // 列名称
        if (tableList.length === 0 || tableList[1][0] === '未查询到数据') return { table: [], header }

        const info = {}
        for (let i = 1; i < tableList.length; i++) {
          const term1 = tableList[i][1]
          if ((term1 in info) === false) { info[term1] = [] }
          const tem = []
          columnNeed.forEach((idx) => {
            if (idx === 5) {
              const scor = { }
              if (/\d+/.test(tableList[i][idx])) {
                scor.score = +tableList[i][idx]
              } else {
                scor.score = tableList[i][idx]
              }
              tem.push(scor)
            }
            else { tem.push(tableList[i][idx]) }
          })
          info[term1].push(tem)
        }
        return { table: info, header }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, header: [] }
  }

  /**
   * * 成绩占比数据请求
   * @param {string} link 占比详情请求地址
   * @return {Object} *
   */
  async proportion(link) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = encodeURI(link)
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        return tableList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return {}
  }
}
